/*
 * ActionHandler.java
 * 
 * @version 1.0, March 6, 2011
 * CS 2340 Team 10: Cyberdyne Systems
 */
package edu.gatech.oad.cyberdoc.domain.action;

import java.util.logging.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import edu.gatech.oad.cyberdoc.domain.User;

/**
 * An interface to define the requirements of a class that is able to handle one
 * or more actions sent from the front-end to the server through a command.
 * 
 * @author John Girata
 * @version 1.0, March 6, 2011
 * 
 */
public abstract class ActionHandler {

	/**
	 * The logger for this class.
	 */
	private static final Logger LOG;

	static {
		LOG = Logger.getLogger("edu.gatech.oad.cyberdoc.action."
				+ "ActionHandler");
	}

	/**
	 * Logs the construction of this ActionHandler.
	 */
	public ActionHandler() {
		String name = getClass().getName();
		name = name.substring(name.lastIndexOf('.') + 1);

		LOG.info("Starting handler " + name);
	}

	/**
	 * A convenience method for allowing one ActionHandler to call another. This
	 * alleviates the need for either passing instances of ActionHandler arround
	 * or using singleton classes.
	 * 
	 * @param action
	 *            The action code of the handler to call
	 * @param command
	 *            The command for the handler to execute
	 * @return The result of handling the action
	 * @throws ActionHandleException
	 *             If the handler throws an ActionHandleException
	 * @throws JSONException
	 *             If the handler throws a JSONException
	 */
	public static JSONObject pass(String action, JSONObject command)
			throws ActionHandleException, JSONException {
		final String old = command.getString("action");
		command.put("action", action);

		final JSONObject response = User.handleCommand(command);
		response.put("action", old);

		return response;
	}

	/**
	 * The method that will handle the action(s).
	 * 
	 * @param source
	 *            The object which is performing this action
	 * @param command
	 *            The command encoding the action
	 * @return The result of performing this action
	 * @throws ActionHandleException
	 *             If an error occurs while trying to handle this action
	 */
	public abstract JSONObject handle(User source, JSONObject command)
			throws ActionHandleException;

	/**
	 * This method should "clean-up" after the action handler. That is, anything
	 * done by the action handler during construction should be reverted by this
	 * method. This method is used in testing to return the system back to its
	 * "clean" form to prevent collisions with later tests. However, this method
	 * should not revert changes made by the handle() method.
	 */
	public abstract void destroy();
}
